import time
import sys
from datetime import datetime

class SmartLogger:
    LEVELS = {
        'DEBUG':    {'color': '\033[94m', 'order': 10},
        'INFO':     {'color': '\033[92m', 'order': 20},
        'WARNING':  {'color': '\033[93m', 'order': 30},
        'ERROR':    {'color': '\033[91m', 'order': 40},
        'CRITICAL': {'color': '\033[95m', 'order': 50},
    }
    RESET = '\033[0m'

    def __init__(self, min_level='DEBUG', log_file=None):
        self.min_level = min_level
        self.log_file = log_file
        self.stats = {level: 0 for level in self.LEVELS}
        if log_file:
            self.file = open(log_file, 'a', encoding='utf-8')
        else:
            self.file = None

    def _should_log(self, level):
        return self.LEVELS[level]['order'] >= self.LEVELS[self.min_level]['order']

    def _log(self, level, msg):
        if not self._should_log(level):
            return
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        color = self.LEVELS[level]['color']
        formatted = f"{color}[{level}] {timestamp}: {msg}{self.RESET}"
        print(formatted)
        if self.file:
            self.file.write(f"[{level}] {timestamp}: {msg}\n")
        self.stats[level] += 1

    def debug(self, msg):    self._log('DEBUG', msg)
    def info(self, msg):     self._log('INFO', msg)
    def warning(self, msg):  self._log('WARNING', msg)
    def error(self, msg):    self._log('ERROR', msg)
    def critical(self, msg): self._log('CRITICAL', msg)

    def print_table(self, headers, rows):
        # 自动计算列宽
        col_widths = [len(str(h)) for h in headers]
        for row in rows:
            for i, cell in enumerate(row):
                col_widths[i] = max(col_widths[i], len(str(cell)))
        # 打印表头
        header_line = ' | '.join(str(h).ljust(col_widths[i]) for i, h in enumerate(headers))
        sep_line = '-+-'.join('-' * w for w in col_widths)
        print(header_line)
        print(sep_line)
        # 打印数据行
        for row in rows:
            print(' | '.join(str(cell).ljust(col_widths[i]) for i, cell in enumerate(row)))

    def report(self):
        print("日志统计报告：")
        for level in self.LEVELS:
            print(f"{level}: {self.stats[level]}")

    def set_min_level(self, level):
        if level in self.LEVELS:
            self.min_level = level

    def __del__(self):
        if self.file:
            self.file.close()

# 使用示例
if __name__ == "__main__":
    logger = SmartLogger(min_level='DEBUG', log_file='log.txt')
    logger.debug("调试信息")
    logger.info("普通信息")
    logger.warning("警告信息")
    logger.error("错误信息")
    logger.critical("严重错误信息")
    logger.print_table(
        headers=["姓名", "年龄", "成绩"],
        rows=[["张三", 18, 90], ["李四", 19, 85], ["王五", 20, 88]]
    )
    logger.report()